package utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class UXml {
	
	/**
	 * 
	 * @param doc
	 * @return
	 * @throws TransformerException
	 */
	public static byte[] doc2Bytes(Document doc) throws TransformerException {
		
		Source source = new DOMSource(doc);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Result result = new StreamResult(out);
        
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(source, result);
        
        return out.toByteArray();
	}
	
	
	/**
	 * 
	 * @param bArray
	 * @return
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 */
	public static Document bytes2Doc(byte[] bArray) throws ParserConfigurationException, SAXException, IOException {
		
		DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		InputSource is = new InputSource();
		
		is.setByteStream(new ByteArrayInputStream(bArray));
		
		return parser.parse(is);
	}
	
}
